import axios from "axios";
import UIResult from "../ui-result";
const BASE_URL = "/api/"
// const BASE_URL = "https://www.wanandroid.com/"

const httpClient = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});


// 添加请求拦截器
// httpClient.interceptors.request.use(function (config) {
//   // 在发送请求之前做些什么
//   return config;
// }, function (error) {
//   // 对请求错误做些什么
//   return Promise.reject(error);
// });

// 添加响应拦截器
httpClient.interceptors.response.use(function (res) {
  const httpStatus = res.status
  const httpMsg = res.statusText
  if (httpStatus === 200) {
    const data = res.data;
    const msg = data.errorMsg;
    const code = data.errorCode;
    if (code === 0) {
      // return Promise.resolve(new UIResult(code, msg, data.data))
    //   return Promise.resolve(data.data)
      return data
    } else {
      return convertError(code, msg)
    }
  } else {
    return convertError(httpStatus, httpMsg)
  }
}, function (error) {
  const res = error.response
  return convertError(res.status, res.statusText)
});

/**
 * 统一错误处理，如果不是有特定的错误逻辑，UI层大部分情况下不需要接收error消息
 * @param {number} code 
 * @param {string} msg 
 * @returns Promise
 */
function convertError(code:number, msg:string) {
  return Promise.reject(UIResult.error(code, msg))
}



export default httpClient
